<?php
/**
 * Created by PhpStorm.
 * FileName: Appointment.class.php
 * User: Administrator
 * Date: 2018/4/16
 * Time: 10:02
 */

namespace Api\Controller;

use Admin\Model\AirwayModel;
use Admin\Model\AttachmentModel;
use Admin\Model\MoneyModel;
use Admin\Model\OrderModel;
use Admin\Model\OrderReviewModel;
use Admin\Model\OrderStatusHistoryModel;
use Admin\Model\TripModel;
use Admin\Model\UserModel;
use Common\Lib\Util\LogUtil;
use Common\Lib\Util\ToolUtil;
use Org\Util\String;

class OrderController extends ApiController {

    private $tripModel;
    private $orderModel;
    private $userModel;
    private $attachmentModel;
    private $airwayModel;
    private $stateList;
    private $moneyModel;
    private $orderReviewModel;
    private $orderStatusHistoryModel;

    public function __construct() {
        parent::__construct();
        $this->tripModel = new TripModel();
        $this->orderModel = new OrderModel();
        $this->userModel = new UserModel();
        $this->attachmentModel = new AttachmentModel();
        $this->airwayModel = new AirwayModel();
        $this->moneyModel = new MoneyModel();
        $this->orderReviewModel = new OrderReviewModel();
        $this->orderStatusHistoryModel = new OrderStatusHistoryModel();

        // 订单状态标签、描述、状态变更规则及该状态下可执行的操作 buyer 已抢行程 | seller 被抢行程
        $this->stateList = array(
            '0' => array('label' => '已抢单','desc' => '%s已抢单，等待%s接单', 'action' => array(
                    'buyer' => array(array('type' => 'cancel')), // 取消
                    'seller' => array(array('type' => 'accept'),array('type' => 'refuse')), // 接单，拒绝
                ), 'rule' => array(1,5,7)
            ),
            '1' => array('label' => '已接单','desc' => '%s已接单，任意一方点击"开始执行"后双方将不能取消订单', 'action' => array(
                    'buyer' => array(array('type' => 'cancel')), // 取消，开始执行（动态添加，预付款为0时存在）
                    'seller' => array(array('type' => 'cancel')), // 取消，开始执行（动态添加，预付款非0时存在）
                ), 'rule' => array(2,5)
            ),
            '2' => array('label' => '执行中','desc' => '%s已标记开始执行', 'action' => array(
                    'buyer' => array(),
                    'seller' => array(array('type' => 'done'),array('type' => 'harded')), // 确认完成，已尽力
                ), 'rule' => array(3,4)
            ),
            '3' => array('label' => '已确认','desc' => '%s已确认完成，%s', 'action' => array(
                    'buyer' => array(array('type' => 'yes'),array('type' => 'no')), // 同意，不同意
                    'seller' => array(),
                ), 'rule' => array(2,8)
            ),
            '4' => array('label' => '已尽力','desc' => '%s已尽力，%s', 'action' => array(
                    'buyer' => array(array('type' => 'yes'),array('type' => 'no-harded')), // 同意，未尽力
                    'seller' => array(),
                ), 'rule' => array(6,8)
            ),
            '5' => array('label' => '已取消','desc' => '%s已取消订单', 'action' => array(
                    'buyer' => array(array('type' => 'delete')), // 删除
                    'seller' => array(array('type' => 'delete')),// 删除
                ), 'rule' => array(9)
            ),
            '6' => array('label' => '已取消','desc' => '%s未完成', 'action' => array(
                    'buyer' => array(array('type' => 'delete')), // 评论，删除
                    'seller' => array(array('type' => 'delete')), // 评论，删除
                ), 'rule' => array(9)
            ),
            '7' => array('label' => '已取消','desc' => '%s拒绝接单', 'action' => array(
                    'buyer' => array(array('type' => 'delete')),// 删除
                    'seller' => array(array('type' => 'delete')),// 删除
                ), 'rule' => array(9)
            ),
            '8' => array('label' => '已完成','desc' => '订单结束', 'action' => array(
                    'buyer' => array(array('type' => 'delete')), // 评论，删除
                    'seller' => array(array('type' => 'delete')), // 评论，删除
                ), 'rule' => array(9)
            )
        );
    }

    // 我的订单列表
    public function myList() {
        $where = array();
        $user_id = I('user_id');
        if (!$user_id) {
            $this->callBack('无效的参数',$this->ERROR_CODE);
        }
        $userWhere['buyer_id'] = $user_id;
        $userWhere['seller_id'] = $user_id;
        $userWhere['_logic'] = 'or';
        $where['_complex'] = $userWhere;
        $pageSize = 15;
        $curPage = I('p',1);
        $data = $this->orderModel->getList($where,$pageSize,$curPage);
        return $this->callBack("订单列表",$this->SUCCESS_CODE,$data);
    }

    // 我的订单列表 - 已抢行程
    public function buyerOrders() {
        $state = I('state');
        $where = array('state' => array('lt',9));
        switch ($state) {
            case '1':
                // 进行中
                $where = array('state' => array('in',array(0,1,2,3,4)));
                break;
            case '2':
                // 已取消
                $where = array('state' => array('in',array(5,6,7)));
                break;
            case '3':
                // 已完成
                $where = array('state' => array('in',array(8)));
                break;
        }
        $user_id = I('user_id');
        if (!$user_id) {
            $this->callBack('无效的参数',$this->ERROR_CODE);
        }
        $where['buyer_id'] = $user_id;
        // 小程序端只显示货运订单
        $where['type'] = 1;
        $pageSize = 15;
        $curPage = I('p',1);
        $data = $this->orderModel->getList($where,$pageSize,$curPage);
        $list = $data['list'];
        foreach ($list as $key => $item) {
            $state_desc = $this->stateList[$item['state']]['desc'];
            $is_self = $item['buyer_id'] == $item['last_operator_id'];
            switch ($item['state']) {
                case '0':
                    $state_desc = sprintf($state_desc,'您','对方');
                    break;
                case '1':
                    $state_desc = sprintf($state_desc,'对方');
                    break;
                case '2':
                    $state_desc = sprintf($state_desc,$is_self ? '您' : '对方');
                    break;
                case '3':
                    $state_desc = sprintf($state_desc,'对方','请您确认');
                    break;
                case '4':
                    $state_desc = sprintf($state_desc,'对方','但未完成');
                    break;
                case '5':
                    $state_desc = sprintf($state_desc,$is_self ? '您' : '对方');
                    break;
                case '6':
                    $state_desc = sprintf($state_desc,'对方');
                    break;
                case '7':
                    $state_desc = sprintf($state_desc,'您被');
                    break;
                case '8':
                    break;
            }
            $list[$key]['state_text'] = $this->stateList[$item['state']]['label'];
            $list[$key]['state_desc'] = $state_desc;
            $actionList = $this->stateList[$item['state']]['action']['buyer'];
            // 已接单状态下，预付款为0时，加入[开始执行]按钮
            if ($item['state'] == 1 && $item['deposit'] <= 0) {
                $actionList[] = array('type' => 'start');
            }
            // 加入评论按钮
            if (!$item['review'] && in_array($item['state'],array('6','8'))) {
                $actionList[] = array('type' => 'comment');
            }
            $list[$key]['action'] = $actionList;
        }
        $data['list'] = $list;
        return $this->callBack("订单列表",$this->SUCCESS_CODE,$data);
    }

    // 我的订单列表 - 被抢行程
    public function sellerOrders() {
        $state = I('state');
        $where = array('state' => array('lt',9));
        switch ($state) {
            case '1':
                // 进行中
                $where = array('state' => array('in',array(0,1,2,3,4)));
                break;
            case '2':
                // 已取消
                $where = array('state' => array('in',array(5,6,7)));
                break;
            case '3':
                // 已完成
                $where = array('state' => array('in',array(8)));
                break;
        }
        $user_id = I('user_id');
        if (!$user_id) {
            $this->callBack('无效的参数',$this->ERROR_CODE);
        }
        $where['seller_id'] = $user_id;
        // 小程序端只显示货运订单
        $where['type'] = 1;
        $pageSize = 15;
        $curPage = I('p',1);
        $data = $this->orderModel->getList($where,$pageSize,$curPage);
        $list = $data['list'];
        foreach ($list as $key => $item) {
            $state_desc = $this->stateList[$item['state']]['desc'];
            $is_self = $item['seller_id'] == $item['last_operator_id'];
            switch ($item['state']) {
                case '0':
                    $state_desc = sprintf($state_desc,'对方','您');
                    break;
                case '1':
                    $state_desc = sprintf($state_desc,'您');
                    break;
                case '2':
                    $state_desc = sprintf($state_desc,$is_self ? '您' : '对方');
                    break;
                case '3':
                    $state_desc = sprintf($state_desc,'您','等待对方确认');
                    break;
                case '4':
                    $state_desc = sprintf($state_desc,'您','等待对方确认');
                    break;
                case '5':
                    $state_desc = sprintf($state_desc,$is_self ? '您' : '对方');
                    break;
                case '6':
                    $state_desc = sprintf($state_desc,'');
                    break;
                case '7':
                    $state_desc = sprintf($state_desc,'您已');
                    break;
                case '8':
                    break;
            }
            $list[$key]['state_text'] = $this->stateList[$item['state']]['label'];
            $list[$key]['state_desc'] = $state_desc;
            $actionList = $this->stateList[$item['state']]['action']['seller'];
            // 已接单状态下，预付款大于0时，加入[开始执行]按钮
            if ($item['state'] == 1 && $item['deposit'] > 0) {
                $actionList[] = array('type' => 'start');
            }
            // 加入评论按钮
            if (!$item['review'] && in_array($item['state'],array('6','8'))) {
                $actionList[] = array('type' => 'comment');
            }
            $list[$key]['action'] = $actionList;
        }
        $data['list'] = $list;
        return $this->callBack("订单列表",$this->SUCCESS_CODE,$data);
    }

    // 订单明细
    public function detail() {
        $id = I('id');
        $user_id = I('user_id');
        if (!$id) {
            $this->callBack('无效的参数',$this->ERROR_CODE);
        }
        $data = $this->orderModel->detail(array('id' => $id,'user_id' => $user_id));
        $userType = '';
        if ($user_id == $data['buyer_id']) {
            $userType = 'buyer';
        } else if ($user_id == $data['seller_id']) {
            $userType = 'seller';
        }
        $actionList = $this->stateList[$data['state']]['action'][$userType];
        // 已接单状态下，预付款大于0时，加入[开始执行]按钮
        if ($data['state'] == 1 && $data['deposit'] > 0) {
            $actionList[] = array('type' => 'start');
        }
        // 加入评论按钮
        if (!$data['review'] && in_array($data['state'],array('6','8'))) {
            $actionList[] = array('type' => 'comment');
        }
        $data['action'] = $actionList;
        $contact = array();
        if ($data['contact']['tel']) {
            $contact[] = array('type' => 'tel', 'value' => $data['contact']['tel']);
        }
        if ($data['contact']['wx']) {
            $contact[] = array('type' => 'wx', 'value' => $data['contact']['wx']);
        }
        $data['contact'] = $contact;
        $data['statusHistory'] = $this->getOrderStatusHistory($id,$data['state']);
        return $this->callBack("订单明细",$this->SUCCESS_CODE,$data);
    }

    // 创建订单
    public function create() {
        $data = array();
        $user_id = I('user_id');
        $trip_id = I('trip_id');
        $contact = I('contact');
        $type = I('type');
        if (!$user_id || !$trip_id) {
            $this->callBack('无效的参数',$this->ERROR_CODE);
        }
        if ($this->getProcessBuyerOrderNum($user_id) >= $this->userLevelInfo['buyer_order_max']) {
            return $this->callBack('您的抢单数量已达上限！',$this->ERROR_CODE);
        }
        $seller_id = $this->tripModel->where(array('id' => $trip_id))->getField('user_id');
        if (!$seller_id) {
            $this->callBack('无效的订单信息',$this->ERROR_CODE);
        }
        $data['buyer_id'] = $user_id;
        $data['trip_id'] = $trip_id;
        $data['reward'] = I('reward');
        $data['deposit'] = I('deposit');
        $data['brokerage'] = I('brokerage');
        $data['remark'] = I('remark');
        $data['seller_id'] = $seller_id;
        $data['type'] = $type;
        $data['status'] = ($type == 1) ? 1 : 3;
        $data['state'] = ($type == 1) ? 0 : 8;
        $data['last_operator_id'] = $user_id;
        $contacts = array();
        $contact_tmp = explode('|',$contact);
        foreach ($contact_tmp as $tmps) {
            $item = explode(':',$tmps);
            if (!trim($item[1])) {
                continue;
            }
            $contacts[trim($item[0])] = trim($item[1]);
        }
        if ($contacts) {
            $data['contact'] = json_encode($contacts,JSON_UNESCAPED_UNICODE);
        }
        $rs = $this->orderModel->add($data);
        if ($rs !== false) {
            if ($type == 1) {
                // 货运订单处理逻辑
                $attachmentIds = I('attache');
                $removedIds = I('removed');
                $this->handleAttache($rs,$attachmentIds,$removedIds);
                $this->addOrderStatusHistory($rs,0,$user_id,'下单成功！');
                //$this->updateTransactionId($rs,$user_id,$trip_id);
                // 通知推送处理
                $this->handleWXNotice($rs,'','下单成功！');
            } else if ($type == 2) {
                // 查询联系方式订单处理逻辑
                $money = $data['reward'];
                $this->userModel->where(array('id' => $seller_id))->setInc('money',$money);
                // 资金流水处理
                //$this->handleCapitalFlow($seller_id,$money,1,'客户查询联系方式金额');
                //$this->updateTransactionId($rs,$user_id,$trip_id);
            }
            return $this->callBack('订单创建成功！',$this->SUCCESS_CODE);
        }
        return $this->callBack('订单创建失败！',$this->ERROR_CODE);
    }

    // 创建订单
    public function createOrder($orderData,$out_trade_no,$transaction_id) {
        LogUtil::info($orderData);
        $data = array();
        $user_id = $orderData['user_id'];
        $trip_id = $orderData['trip_id'];
        $contact = $orderData['contact'];
        $type = $orderData['type'];
        $info = array('out_trade_no' => $out_trade_no, 'transaction_id' => $transaction_id);
        if (!$user_id || !$trip_id) {
            $info['msg'] = '无效的参数';
            LogUtil::info($info);
            return false;
        }
        if ($this->getProcessBuyerOrderNum($user_id) >= $this->getBuyerOrderMax($user_id)) {
            $info['msg'] = '您的抢单数量已达上限！';
            return false;
        }
        $seller_id = $this->tripModel->where(array('id' => $trip_id))->getField('user_id');
        if (!$seller_id) {
            $info['msg'] = '无效的订单信息！';
            LogUtil::info($info);
            return false;
        }
        $data['buyer_id'] = $user_id;
        $data['trip_id'] = $trip_id;
        $data['reward'] = $orderData['reward'];
        $data['deposit'] = $orderData['deposit'];
        $data['brokerage'] = $orderData['brokerage'];
        $data['remark'] = $orderData['remark'];
        $data['seller_id'] = $seller_id;
        $data['type'] = $type;
        $data['status'] = ($type == 1) ? 1 : 3;
        $data['state'] = ($type == 1) ? 0 : 8;
        $data['last_operator_id'] = $user_id;
        $data['transaction_id'] = $transaction_id;
        $data['order_no'] = String::randString(9,1);
        $contacts = array();
        $contact_tmp = explode('|',$contact);
        foreach ($contact_tmp as $tmps) {
            $item = explode(':',$tmps);
            if (!trim($item[1])) {
                continue;
            }
            $contacts[trim($item[0])] = trim($item[1]);
        }
        if ($contacts) {
            $data['contact'] = json_encode($contacts,JSON_UNESCAPED_UNICODE);
        }
        $rs = $this->orderModel->add($data);
        if ($rs !== false) {
            if ($type == 1) {
                // 货运订单处理逻辑
                $attachmentIds = $orderData['attache'];
                $removedIds = $orderData['removed'];
                $this->handleAttache($rs,$attachmentIds,$removedIds);
                $this->addOrderStatusHistory($rs,0,$user_id,'下单成功！');
                // 通知推送处理
                $this->handleWXNotice($rs,$orderData['form_id'],'下单成功通知');
            } else if ($type == 2) {
                // 查询联系方式订单处理逻辑
                $money = $data['reward'];
                $this->userModel->where(array('id' => $seller_id))->setInc('money',$money);
                // 资金流水处理
                //$this->handleCapitalFlow($seller_id,$money,1,'客户查询联系方式金额');
            }
            $info['msg'] = '订单创建成功！';
            LogUtil::info($info);
            F($out_trade_no,null);
            return true;
        }
        $info['msg'] = '订单创建失败！';
        LogUtil::info($info);
        return false;
    }

    // 订单状态变更
    public function changeStatus() {
        $id = I('id');
        $state = I('state');
        $user_id = I('user_id');
        $form_id = I('form_id');
        if (!$id || !$state || !$user_id) {
            $this->callBack('无效的参数',$this->ERROR_CODE);
        }
        // 查询订单当前状态
        $currentState = $this->orderModel->where(array('id' => $id))->getField('state');
        if (!in_array($state,$this->stateList[$currentState]['rule'])) {
            $msg = sprintf('该订单状态无法修改！当前状态：%s',$this->stateList[$currentState]['label']);
            return $this->callBack($msg,$this->ERROR_CODE);
        }
        if ($state == 1) {
            $seller_id = $this->orderModel->where(array('id' => $id))->getField('seller_id');
            if ($this->getProcessSellerOrderNum($seller_id) >= $this->userLevelInfo['seller_order_max']) {
                return $this->callBack('您的接单数量已达上限！',$this->ERROR_CODE);
            }
        }
        $rs = $this->orderModel->update(array('state' => $state,'last_operator_id' => $user_id),array('id' => $id));
        if ($rs !== false) {
            // 行程状态处理
            $this->handleTripState($id);
            // 订单付款处理
            $this->handleOrderAmount($id,$currentState,$state,$user_id);
            // 信誉分处理
            $this->handleCredit($id,$currentState,$state,$user_id);
            // 添加订单状态变更记录
            $this->addOrderStatusHistory($id,$state,$user_id);
            // 通知推送处理
            $this->handleWXNotice($id,$form_id,'订单状态变更通知',$user_id);
            return $this->callBack('订单状态变更成功！',$this->SUCCESS_CODE);
        }
        return $this->callBack('订单状态变更失败！',$this->ERROR_CODE);
    }

    // 获取正在进行中的已抢订单数量
    private function getProcessBuyerOrderNum($user_id) {
        $count = $this->orderModel->where(array('buyer_id' => $user_id,'state' => array('in',array('0','1','2'))))->count();
        return $count;
    }

    // 获取正在进行中的已接订单数量
    private function getProcessSellerOrderNum($user_id) {
        $count = $this->orderModel->where(array('seller_id' => $user_id,'state' => array('in',array('1','2'))))->count();
        return $count;
    }

    //处理附件
    private function handleAttache($rel_id,$attachmentIds,$removedIds){
        $this->attachmentModel->deleteAttachement($removedIds);
        $this->attachmentModel->updateAttachement(array('rel_id'=>$rel_id),$attachmentIds);
    }

    // 资金流水处理
    private function handleCapitalFlow ($userId,$money=0,$type=0,$remark='') {
        $moneyData = array(
            'user_id' => $userId,
            'money' => $money,
            'type' => $type,
            'remark' => $remark
        );
        $this->moneyModel->add($moneyData);
    }

    // 行程状态处理
    private function handleTripState($orderId) {
        $order = $this->orderModel->where(array('id' => $orderId))->find();
        $tripId = $order['trip_id'];
        $count = $this->orderModel->where(array('trip_id' => $tripId,'state' => array('in',array('1','2'))))->count();
        if ($count >= $this->userLevelInfo['seller_order_max']) {
            // 如果接单状态已达上限，将行程状态修改为[订单已满]
            $this->tripModel->update(array('state' => 2),array('id' => $tripId));
        }
    }

    // 订单付款处理
    private function handleOrderAmount($orderId,$currentState,$state,$user_id) {
        $order = $this->orderModel->where(array('id' => $orderId))->find();
        if (($currentState == 2 && $state == 3) || ($currentState == 3 && $state == 8)) {
            if ($order['seller_id'] == $user_id) {
                // 旅客点击【确认完成】或【同意对方完成】
                // 旅客确认完成，更新实际花费金额，实际花费金额应小于等于预付款deposit
                $total = I('total',0);
                $total = $total>0 ? $total : $order['deposit'];
                $total = min(array($total,$order['deposit']));
                $this->orderModel->update(array('total' => $total),array('id' => $orderId));
            } else if ($order['buyer_id'] == $user_id) {
                // 客户点击【确认完成】或【同意对方完成】
                // 客户确认完成，将预付款（保证金）和赏金支付给旅客
                $money = $order['deposit']+$order['reward'];
                $this->userModel->where(array('id' => $order['seller_id']))->setInc('money',$money);
                // 资金流水处理
                $this->handleCapitalFlow($order['seller_id'],$money,0,'客户确认订单完成，预付款+报酬');
            }
        } else if ($currentState == 4 && $state == 8) {
            // 旅客已尽力，但未完成，客户确认后，将车马费支付给旅客，将赏金减去车马费后剩余的金额，支付给客户
            $tip = I('tip',0);
            $tip = min(array($tip,$order['reward']));
            $this->orderModel->update(array('tip' => $tip),array('id' => $orderId));
            $this->userModel->where(array('id' => $order['seller_id']))->setInc('money',$tip);
            $this->userModel->where(array('id' => $order['buyer_id']))->setInc('money',$order['reward']-$tip);
            // 资金流水处理
            $this->handleCapitalFlow($order['seller_id'],$tip,0,'客户确认旅客已尽力，车马费');
            $this->handleCapitalFlow($order['buyer_id'],$order['reward']-$tip,0,'客户确认旅客已尽力，报酬-车马费');
        } else if (in_array($state,array(5,6,7))) {
            // 订单取消后，将预付款（保证金）和赏金退还给客户
            $money = $order['deposit']+$order['reward'];
            $this->userModel->where(array('id' => $order['buyer_id']))->setInc('money',$money);
            // 资金流水处理
            $msg = '订单取消，退款至客户，订单编号：'.$order['order_no'];
            $this->handleCapitalFlow($order['buyer_id'],$money,3,$msg);
        }
    }

    // 信誉值处理
    private function handleCredit ($orderId,$currentState,$state,$user_id) {
        $order = $this->orderModel->where(array('id' => $orderId))->find();
        // 已接单状态下，取消订单后的信誉值处理
        if ($currentState == 1 && $state == 5) {
            if ($order['buyer_id'] == $user_id) {
                // 客户取消，扣减客户信誉值
                $this->userModel->where(array('id' => $order['buyer_id']))->setDec('credit',$this->sysConfig['buyer_credit_dec_cancel']);
            } else if ($order['seller_id'] == $user_id) {
                // 旅客取消，扣减旅客信誉值
                $this->userModel->where(array('id' => $order['seller_id']))->setDec('credit',$this->sysConfig['seller_credit_dec_cancel']);
            }
        } else if ($currentState == 4 && $state == 6) {
            // 未尽力状态下，扣减旅客信誉值
            $this->userModel->where(array('id' => $order['seller_id']))->setDec('credit',$this->sysConfig['seller_credit_dec_no_harded']);
        } else if ($currentState == 3 && $state == 8) {
            // 双方确认完成后，增加各自信誉值
            $this->userModel->where(array('id' => $order['buyer_id']))->setInc('credit',$this->sysConfig['credit_inc_success']);
            // 行程中如果旅客有取消过其它订单，则旅客不增加信誉值
            $count = $this->orderModel->where(array('trip_id' => $order['trip_id'],'state' => 5))->where('seller_id=last_operator_id')->count();
            if ($count == 0) {
                $this->userModel->where(array('id' => $order['seller_id']))->setInc('credit',$this->sysConfig['credit_inc_success']);
            }
        }
    }

    private function getOrderStatusHistory($orderId,$state) {
        $result = array(
            '0' => array('status' => 0,'status_text' => '已下单','user_id' => '','user_name' => '','add_time' => '','is_current' => false,'is_end' => false),
            '1' => array('status' => 1,'status_text' => '已接单','user_id' => '','user_name' => '','add_time' => '','is_current' => false,'is_end' => false),
            '2' => array('status' => 2,'status_text' => '已开始','user_id' => '','user_name' => '','add_time' => '','is_current' => false,'is_end' => false),
            '3' => array('status' => 3,'status_text' => '已确认','user_id' => '','user_name' => '','add_time' => '','is_current' => false,'is_end' => false),
            '4' => array('status' => 4,'status_text' => '已尽力','user_id' => '','user_name' => '','add_time' => '','is_current' => false,'is_end' => false),
            '5' => array('status' => 5,'status_text' => '已取消','user_id' => '','user_name' => '','add_time' => '','is_current' => false,'is_end' => false),
            '6' => array('status' => 6,'status_text' => '未完成','user_id' => '','user_name' => '','add_time' => '','is_current' => false,'is_end' => false),
            '7' => array('status' => 7,'status_text' => '拒绝接单','user_id' => '','user_name' => '','add_time' => '','is_current' => false,'is_end' => false),
            '8' => array('status' => 8,'status_text' => '已完成','user_id' => '','user_name' => '','add_time' => '','is_current' => false,'is_end' => false),
        );
        $where = array(
            'order_id' => $orderId,
            'status' => array('in',array_keys($result))
        );

        $orderStatusHistory = $this->orderStatusHistoryModel->getList($where);
        $tmpStatus = array();
        foreach ($orderStatusHistory as $key => $item) {
            if ($item['status'] == $state) {
                $result[$item['status']]['is_current'] = true;
            }
            if ($item['status'] < $state) {
                $result[$item['status']]['is_end'] = true;
            }
            $result[$item['status']]['add_time'] = $item['add_time'];
            $result[$item['status']]['user_name'] = $item['user']['real_name'];
            $result[$item['status']]['user_id'] = $item['user_id'];
            $result[$item['status']]['city'] = $item['city'];
        }
        $res = array();
        $cbResult = ToolUtil::array_sort($result,'add_time','asc',false);
        foreach ($cbResult as $key => $value) {
            if (!$value['add_time']) {
                continue;
            }
            $tmpStatus[] = $value['status'];
            $res[] = $value;
        }
        $trendStatus = $this->stateList[$state]['rule'];
        foreach ($trendStatus as $item) {
            if (in_array($item,$tmpStatus)) {
                continue;
            }
            if (!$result[$item]) {
                continue;
            }
            $res[] = $result[$item];
        }
        $res = array_slice($res,max(count($res),5)-5,5);
        return $res;
    }

    private function handleWXNotice($orderId,$form_id,$title='',$user_id='') {
        $templateId = C('WEIXIN_TEMPLATE_ORDER_STATUS');
        $row = $this->orderModel->detail(array('id' => $orderId,'user_id' => $user_id));
        $trip = $this->tripModel->where(array('id' => $row['trip_id']))->find();
        $orderAmount = $row['reward']+$row['deposit']+$row['brokerage'];
        $toUser = '';
        if ($row['last_operator_id'] == $row['buyer_id']) {
            // 如果最后操作人是客户，则将信息推送给旅客
            //$toUser = 'seller';
            $toUser = 'buyer';
        } else if ($row['last_operator_id'] == $row['seller_id']) {
            // 如果最后操作人是旅客，则将信息推送给客户
            //$toUser = 'buyer';
            $toUser = 'seller';
        }
        $option = array(
            // 订单编号
            'keyword1' => array('value' => sprintf('%s',$row['id'])),
            // 行程路线
            'keyword2' => array('value' => sprintf('%s',$trip['origin'].' - '.$trip['destination'])),
            // 出发日期
            'keyword3' => array('value' => date('Y年m月d日',$trip['depart_date'])),
            // 行程状态
            'keyword4' => array('value' => sprintf('%s',$this->stateList[$row['state']]['label'])),
            // 旅客昵称
            'keyword5' => array('value' => sprintf('%s',$row['seller']['user_name'])),
            // 客户昵称
            'keyword6' => array('value' => sprintf('%s',$row['buyer']['user_name'])),
            // 支付金额
            'keyword7' => array('value' => sprintf('%s',$orderAmount)),
        );
        $options = array(
            'templateId' => $templateId,
            'orderId' => $orderId,
            'openId' => $row[$toUser]['openid'],
            'data' => $option,
            'title' => $title,
            'form_id' => $form_id
        );
        return $this->sendNotice($options);
    }

    //发送微信通知
    private function sendNotice($options) {
        $option = array(
            //接收者openid
            'touser' => $options['openId'],
            //模板ID
            'template_id' => $options['templateId'],
            //模板跳转链接，不填则不用跳转
            'page' => $options['page'] ? $options['page'] : '',
            'form_id' => $options['form_id'],
            //模板数据
            'data' => $options['data']
        );
        $response = sendWenXinNotice($option);
        LogUtil::info($option);
        LogUtil::info($response);
        $result = $response['result'];
        return $result;
    }

    // 添加订单状态变更记录
    private function addOrderStatusHistory($orderId,$status,$userId,$remark='') {
        $data = array(
            'order_id' => $orderId,
            'user_id' => $userId,
            'status' => $status,
            'remark' => $remark,
            'lng' => I('lng'),
            'lat' => I('lat'),
            'province' => I('province'),
            'city' => I('city')
        );
        $this->orderStatusHistoryModel->add($data);
    }

    // 更新微信支付流水
    private function updateTransactionId($rs,$user_id,$trip_id) {
        $where = array(
            'out_trade_no' => sprintf('bd_%s_%s',$user_id,$trip_id)
        );
        $transactionId = M('pay_history')->where($where)->order('id desc')->getField('transaction_id');
        $this->orderModel->update(array('transaction_id' => $transactionId),array('id' => $rs));
    }

    public function addPayHistory() {
        $openid = I('request.openid');
        $out_trade_no = I('request.out_trade_no');
        $total_fee = I('request.total_fee');
        $transaction_id = I('request.transaction_id');
        $status = 1;
        $count = M('pay_history')->where(array('out_trade_no' => $out_trade_no))->count();
        if($count > 0) {
            return true;
        }
        $sql = "insert into pay_history(openid,out_trade_no,total_fee,transaction_id,status,add_time) values ('%s','%s',%s,'%s',%s,%s)";
        $sqlTmp = sprintf($sql,$openid,$out_trade_no,$total_fee,$transaction_id,$status,time());
        M()->execute($sqlTmp);
        $orderData = json_decode(F($out_trade_no),true);
        $this->createOrder($orderData,$out_trade_no,$transaction_id);
        return true;
    }

    private function getBuyerOrderMax($userId) {
        $level = '';
        $credit = M('users')->where(array('id' => $userId))->getField('credit');
        for ($i=1;$i<=5;$i++) {
            if ($credit > $this->sysConfig['level_'.$i]) {
                $level = $i;
                break;
            }
        }
        return $this->sysConfig['buyer_order_max_level_'.$level];
    }

}